package com.kafka.kafkademo.producer;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class KafkaProducerDemo extends Thread{

    private final KafkaProducer<Integer,String> producer;
    private final String topic;
    private final boolean isAsync;

    public KafkaProducerDemo(String topic,boolean isAsync){

        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094");
        properties.put(ProducerConfig.CLIENT_ID_CONFIG,"KafkaProducerDemo");
        properties.put(ProducerConfig.ACKS_CONFIG,"-1");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.IntegerSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,"com.kafka.kafkademo.partition.MyPartition");
        producer = new KafkaProducer<Integer, String>(properties);
        this.topic = topic;
        this.isAsync = isAsync;
    }

    @Override
    public void run() {
        int num = 0;
        while (num < 50){
            String message = "message_" + num;
            System.err.println("begin send message : " + message);

            if(this.isAsync){
                //异步发送
                producer.send(new ProducerRecord<>(topic, message), new Callback() {
                    @Override
                    public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                        if(recordMetadata != null){
                            System.err.println(" async offset" + recordMetadata.offset()
                                    + "patition->" + recordMetadata.partition());
                        }
                    }
                });
            }else {//同步发送
                try {
                    RecordMetadata recordMetadata = producer.send(new ProducerRecord<>(topic,message)).get();
                    System.err.println(" async offset :" + recordMetadata.offset()
                            + ",patition->" + recordMetadata.partition());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            num++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new KafkaProducerDemo("topic2",true).start();
    }
}
